<template>
  <div class="scene-management">
    <!-- 场景列表头部 -->
    <div class="mb-4 flex justify-between" v-if="props.scenes.length > 0 && hasRoles">
      <div class="flex space-x-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索场景"
          class="w-64"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <el-button color="#1c1d29" @click="handleAddScene">
        <el-icon class="mr-1"><Plus /></el-icon>新增场景
      </el-button>
    </div>
    
    <!-- 场景列表 -->
    <el-table
      v-if="filteredScenes.length > 0 && hasRoles"
      :data="filteredScenes"
      style="width: 100%"
      border
      v-loading="loading"
      :row-class-name="getRowClassName"
    >
      <el-table-column prop="sceneName" label="场景名" width="140">
        <template #default="{ row }">
          <div :class="row.status === 'CONFIRM' ? 'scene-cell-container' : 'scene-cell-container disabled-color'">
            <span>{{ row.sceneName }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="sceneDesc" label="场景描述" width="400">
        <template #default="{ row }">
          <el-tooltip
            :content="row.sceneDesc"
            placement="top"
            popper-class="custom-tooltip"
          >
            <div :class="row.status === 'CONFIRM' ? 'scene-cell-container' : 'scene-cell-container disabled-color'">
              <span>{{ row.sceneDesc }}</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      
      <el-table-column label="场景图" width="120">
        <template #default="{ row }">
          <div class="scene-cell-container">
          <div v-if="row.status === 'PROCESSING'" style="color:#3644E0;font-size:14px">AI生成中...</div>
          <el-image
            v-else-if="row.sceneImageUrl"
            :src="row.sceneImageUrl"
            fit="cover"
            class="scene-image"
            @click="previewImage(row.sceneImageUrl)"
          />
          <el-tag 
            v-else 
            type="info" 
            size="small"
            class="scene-image-placeholder"
            @click="openPreGenerateDialog(row)"
          >未上传</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="归属剧集" width="120">
        <template #default="{ row }">
          <div :class="row.status === 'CONFIRM' ? 'scene-cell-container' : 'scene-cell-container disabled-color'">
            <span>{{ row.seriesNo ? `第${row.seriesNo}集` : '暂无' }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="编辑时间" width="180">
        <template #default="{ row }">
          <div :class="row.status === 'CONFIRM' ? 'scene-cell-container' : 'scene-cell-container disabled-color'">
            <span>{{ dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" min-width="180" fixed="right">
        <template #default="{ row }">
          <div v-if="row.status !== 'CONFIRM'" style="display: flex;gap:12px;align-items: center;">
            <el-button color="#1c1d29" size="small" @click="openPreGenerateDialog(row)">
              去确认
            </el-button>
            <span class="txt-btn" @click="handleDeleteScene(row)">删除</span>
          </div>
          <div v-else class="scene-cell-container">
            <span class="txt-btn mr-2" @click="handleEditScene(row)">编辑</span>
            <span class="txt-btn" @click="handleDeleteScene(row)">删除</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 空状态 - 没有角色时 -->
    <div v-if="!hasRoles" class="empty-state">
      <img src="@/assets/images/empty.png" class="empty-image" alt="暂无角色" />
      <p class="empty-text">请先在角色生成页面点击 [完成角色创建] 按钮，完成后可自动生成场景</p>
      <el-button color="#1c1d29" @click="goToRolePage">去完成</el-button>
    </div>

    <!-- 搜索结果为空的状态 -->
    <div v-if="isEmptySearchResult && hasRoles" class="empty-search-state">
      <img src="@/assets/images/empty.png" class="empty-image" alt="无搜索结果" />
      <p class="empty-text">没有符合条件的场景</p>
    </div>

    <!-- 有角色但没有场景时 -->
    <div v-if="!loading && props.scenes.length === 0 && hasRoles" class="empty-state">
      <img src="@/assets/images/empty.png" class="empty-image" alt="暂无场景" />
      <p class="empty-text">暂无场景，点击下方按钮可进入预生成场景图流程</p>
      <el-button color="#1c1d29" @click="handlePregenerate" :loading="pregenerateLoading">预生成</el-button>
    </div>
    
    <!-- 场景弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      width="680px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      destroy-on-close
      custom-class="scene-dialog"
    >
      <template #header>
        <div class="tab-wrapper">
          <div :class="tabName === 'scene' ? 'tab-item active' : 'tab-item'" @click="tabName =  'scene'">手动添加</div>
          <div :class="tabName === 'series' ? 'tab-item active' : 'tab-item'" @click="tabName = 'series'">剧集添加</div>
        </div>
      </template>
      <el-form
        v-show="tabName ===  'scene'"
        ref="sceneFormRef"
        :model="sceneForm"
        :rules="sceneRules"
        label-position="top"
      >
        <el-form-item>
          <template #label>
            <span class="form-label">场景名称<span class="required-mark">*</span></span>
          </template>
          <el-input v-model="sceneForm.sceneName" placeholder="请输入场景名称" maxlength="50" show-word-limit />
        </el-form-item>
        
        <el-form-item>
          <template #label>
            <span class="form-label">场景描述<span class="required-mark">*</span></span>
          </template>
          <el-input 
            v-model="sceneForm.sceneDesc" 
            type="textarea" 
            :rows="3"
            placeholder="请输入场景描述"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <template #label>
            <span class="form-label">所属剧集<span class="required-mark">*</span></span>
          </template>
          <el-select
            v-model="sceneForm.seriesNo"
            placeholder="请选择所属剧集"
            class="w-full"
            :loading="loadingSeries"
            @change="fetchSeriesList"
          >
            <el-option
              v-for="series in seriesList"
              :key="series.seqNo"
              :label="`第${series.seqNo}集`"
              :value="series.seqNo"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <template #label>
            <span class="form-label">场景图<span class="required-mark">*</span></span>
          </template>
          
          <!-- 上传方式切换 -->
          <div class="upload-type-switch mb-2">
            <el-radio-group v-model="uploadType" size="large" text-color="#1c1d29" fill="#fff" >
              <el-radio-button label="local">本地上传</el-radio-button>
              <el-radio-button label="ai">AI生成</el-radio-button>
            </el-radio-group>
          </div>
          
          <!-- 本地上传 -->
          <div v-if="uploadType === 'local'" class="image-upload-container">
              <PicUpload 
                ref="scenePicUpload"
                :editable="true"
                :business-id="sceneForm.sceneId"
                :business-type="'SCENE'"
                :roles="roles"
                :drama-id="props.dramaId"
                @start="beforeImageUpload" 
                @finish="handleImageUpload" 
                @edit="handlePicUploadEdit"
                :defaultUrl="sceneForm.sceneImageUrl" 
              />
              
              <!-- 编辑按钮 - 当有场景图时显示 -->
              <div v-if="sceneForm.sceneImageUrl" class="scene-edit-button-container">
                <el-button 
                  color="#1c1d29"
                  @click="handleSceneImageEdit"
                >
                  编辑场景图
                </el-button>
              </div>
              
              <div class="upload-tips mt-4 p-4 bg-blue-50 rounded-lg text-sm">
                <div class="flex items-start">
                  <el-icon class="mr-2 mt-0.5 text-blue-500"><InfoFilled /></el-icon>
                  <div>
                    <div class="font-medium text-gray-800 mb-1">上传提示</div>
                    <ul class="text-gray-600 list-disc pl-4 space-y-1">
                      <li>建议上传16:9比例的图片，最佳尺寸为1280x720</li>
                      <li>支持JPG、PNG格式，文件大小不超过5MB</li>
                    </ul>
                  </div>
                </div>
              </div>
          </div>
          
          <!-- AI生成 -->
           <div v-else class="ai-tip">
            点击下方按钮将根据场景名称和描述自动生成，确定之后需回到列表进行场景确认
           </div>
      
        </el-form-item>
        
      </el-form>
      <el-form
        v-show="tabName ===  'series'"
        label-position="top"
      >
        <el-form-item>
          <template #label>
            <span class="form-label">所属剧集<span class="required-mark">*</span></span>
          </template>
          <el-select
            v-model="seriesIdList"
            placeholder="请选择"
            class="w-full"
            multiple
          >
            <el-option
              v-for="series in completeCbList"
              :key="series.seriesId"
              :label="`第${series.seqNo}集`"
              :value="series.seriesId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button class="save-el-button" @click="handleDialogClose">取消</el-button>
          <el-button class="save-el-button" color="#1c1d29" @click="handleSaveScene" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 图片预览 -->
    <div v-if="previewVisible" class="image-preview-overlay" @click="previewVisible = false">
      <div class="close-button" @click.stop="previewVisible = false">
          <el-icon><Close /></el-icon>
        </div>
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image" />
      </div>
    </div>

    <!-- 预生成图片弹窗 -->
    <pre-generate-dialog
      v-model:visible="preGenerateVisible"
      :initial-description="currentScenePrompt"
      :scene-id="currentEditingScene?.sceneId"
      @confirm="handlePreGenerateConfirm"
      @cancel="preGenerateVisible = false"
    />

    <!-- 场景图编辑弹窗 -->
    <ImageEditorModal
      v-model:visible="sceneImageEditorVisible"
      :image-url="editingSceneImageUrl"
      :business-id="editingSceneId"
      :business-type="'SCENE'"
      :roles="roles"
      :drama-id="props.dramaId"
      @close="handleSceneImageEditorClose"
      @save="handleSceneImageEditorSave"
    />
  </div>
</template>

<script setup>
import { ref, computed, reactive, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Plus, Edit, Delete, CopyDocument, Upload, Cpu, InfoFilled, RefreshRight, Close } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import { getDramaScene, initSceneList, createScene, createSceneByAI, updateScene, getDramaSeries, getCompleteCbList, generateSceneBySeries } from '@/api/drama'
import PreGenerateDialog from '@/components/common/PreGenerateDialog.vue'
import ImageEditorModal from '@/components/common/ImageEditorModal.vue'
import request from '@/utils/request'
import dayjs from 'dayjs'
import PicUpload from '@/components/common/PicUpload.vue'

const completeCbList = ref([])
const seriesIdList = ref([])

const props = defineProps({
  scenes: {
    type: Array,
    default: () => []
  },
  dramaId: {
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  roles: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:scenes', 'switch-tab'])

// 场景列表
const loading = ref(false)
const pregenerateLoading = ref(false)
const refreshLoading = ref(false)
const searchKeyword = ref('')
const tabName = ref('scene')

// 判断是否有角色
const hasRoles = computed(() => {
  return props.roles && props.roles.length > 0
})

// 搜索处理
const handleSearch = debounce(() => {
  // 搜索逻辑在计算属性中实现
}, 300)

// 过滤后的场景列表
const filteredScenes = computed(() => {
  if (!searchKeyword.value) return props.scenes
  
  const keyword = searchKeyword.value.toLowerCase()
  return props.scenes.filter(scene => 
    scene.sceneName && scene.sceneName.toLowerCase().includes(keyword) || 
    (scene.sceneDesc && scene.sceneDesc.toLowerCase().includes(keyword))
  )
})

// 计算是否为搜索结果为空的状态
const isEmptySearchResult = computed(() => {
  return searchKeyword.value && props.scenes.length > 0 && filteredScenes.value.length === 0
})

// 不再需要这些计算属性，直接在单元格中判断状态
// 获取行的类名，保留以防后续需要
const getRowClassName = ({ row }) => {
  return ''
}

// 跳转到角色页面
const goToRolePage = () => {
  emit('switch-tab', 'role')
}

// 图片预览
const previewVisible = ref(false)
const previewImageUrl = ref('')

const previewImage = (url) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

// 场景表单
const dialogVisible = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const saveLoading = ref(false)
const sceneFormRef = ref(null)
const uploadType = ref('local') // 'local'为本地上传，'ai'为AI生成
const loadingSeries = ref(false) // 加载剧集列表中
const seriesList = ref([]) // 剧集列表

const sceneForm = reactive({
  sceneId: '', // 场景ID
  sceneName: '',
  sceneDesc: '',
  sceneImageUrl: '',
  sceneResKey: '', // 添加sceneResKey字段存储上传后的fileKey
  seriesNo: '' // 所属剧集编号
})

// 表单验证规则
const sceneRules = {
  sceneName: [
    { required: true, message: '请输入场景名称', trigger: 'blur' }
  ],
  sceneDesc: [
    { required: true, message: '请输入场景描述', trigger: 'blur' }
  ],
  seriesNo: [
    { required: true, message: '请选择所属剧集', trigger: 'change' }
  ]
}

// 加载已拆分分镜剧集列表
const fetchCompleteCbList = async () => {
  if (!props.dramaId) return
  const { data } = await getCompleteCbList(props.dramaId)
  if (data && Array.isArray(data)) {
    completeCbList.value = data
  }
}

// 加载剧集列表
const fetchSeriesList = async () => {
  if (!props.dramaId) return
  
  try {
    loadingSeries.value = true
    const { data } = await getDramaSeries(props.dramaId)
    if (data && Array.isArray(data)) {
      seriesList.value = data
    } else {
      seriesList.value = []
    }
  } catch (error) {
    console.error('获取剧集列表失败:', error)
    ElMessage.error('获取剧集列表失败')
    seriesList.value = []
  } finally {
    loadingSeries.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  
  // 重置编辑状态
  isEdit.value = false
  editIndex.value = -1
  
  // 重置表单校验
  nextTick(() => {
    sceneFormRef.value && sceneFormRef.value.resetFields()
  })
}

// 新增场景
const handleAddScene = () => {
  isEdit.value = false
  editIndex.value = -1
  uploadType.value = 'local' // 默认为本地上传
  
  // 重置表单
  Object.keys(sceneForm).forEach(key => {
    sceneForm[key] = ''
  })
  
  // 加载剧集列表
  fetchSeriesList()
  // 加载已拆分剧集列表
  fetchCompleteCbList()
  
  dialogVisible.value = true
  
  // 重置表单校验
  nextTick(() => {
    sceneFormRef.value && sceneFormRef.value.resetFields()
  })
}

// 编辑场景
const handleEditScene = (row) => {
  isEdit.value = true
  editIndex.value = props.scenes.findIndex(item => item.sceneId === row.sceneId)
  
  // 填充表单
  Object.keys(sceneForm).forEach(key => {
    sceneForm[key] = row[key] || ''
  })

  console.log('row', row)
  // 设置上传类型
  uploadType.value = row.sceneImageUrl ? 'local' : 'ai'
  
  // 设置sceneResKey（如果有）
  sceneForm.sceneResKey = row.sceneResKey || ''
  
  // 加载剧集列表
  fetchSeriesList()

  // 加载已拆分剧集列表
  fetchCompleteCbList()
  
  dialogVisible.value = true
  
  // 重置表单校验
  nextTick(() => {
    sceneFormRef.value && sceneFormRef.value.resetFields()
  })
}

// 切换上传类型
const switchUploadType = (type) => {
  uploadType.value = type
  
  // 如果切换到AI生成，清空已上传的图片
  if (type === 'ai') {
    sceneForm.sceneImageUrl = ''
  }
}

// 复制场景
const handleCopyScene = (row) => {
  const newScene = JSON.parse(JSON.stringify(row))
  newScene.id = Date.now() // 生成新ID
  newScene.sceneName = `${newScene.sceneName} (副本)`
  
  const updatedScenes = [...props.scenes, newScene]
  emit('update:scenes', updatedScenes)
  
  ElMessage.success('场景复制成功')
}

// 删除场景
const handleDeleteScene = (row) => {
  ElMessageBox.confirm(`确定要删除场景 "${row.sceneName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: '',
    closeIcon: 'add',
    customClass: 'delete-confirm-dialog',
    confirmButtonClass: 'confirm-delete-btn-class',
    cancelButtonClass: 'cancel-delete-btn-class'
  }).then(async () => {
    try {
      // 调用删除API
      await request.delete(`/evox-drama/scene/${row.sceneId}`)
      
      // 删除成功后刷新场景列表
      const { data } = await getDramaScene(props.dramaId)
      if (data && Array.isArray(data)) {
        emit('update:scenes', data)
      }
      
    ElMessage.success('场景删除成功')
    } catch (error) {
      console.error('删除场景失败:', error)
      ElMessage.error('删除场景失败，请重试')
    }
  }).catch(() => {})
}

// 上传前验证
const beforeImageUpload = (file) => {
  saveLoading.value = true
}

// 处理图片上传
const handleImageUpload = async (fileKey) => {
  sceneForm.sceneResKey = fileKey
  saveLoading.value = false
}

// 预生成场景
const handlePregenerate = async () => {
  try {
    pregenerateLoading.value = true
    loading.value = true
    
    // 调用初始化场景API并通知父组件刷新
    await initSceneList(props.dramaId)
    emit('init-scene') // 触发父组件的tab切换，会重新调用fetchDramaScene
    
    ElMessage.success('场景列表生成请求已提交')
  } catch (error) {
    console.error('预生成场景失败:', error)
    ElMessage.error('预生成失败，请重试')
    loading.value = false
    pregenerateLoading.value = false
  }
}

// 保存场景
const handleSaveScene = async () => {
  if (!sceneForm.sceneName) {
    ElMessage.warning('请输入场景名称')
    return
  }
  if (!sceneForm.sceneDesc) {
    ElMessage.warning('请输入场景描述')
    return
  }
  if (tabName.value === 'scene') {
    // 表单验证
    console.log('sceneFormRef.value', sceneFormRef.value)
  try {
    await sceneFormRef.value.validate()
  } catch (error) {
    return
  }
  
  // 如果是本地上传且没有上传图片，提示用户
  console.log('sceneForm.sceneImageUrl', sceneForm.sceneImageUrl)
  if (uploadType.value === 'local' && !sceneForm.sceneResKey) {
    ElMessage.warning('请上传场景图片')
    return
  }
  
  // 如果是本地上传但没有获取到sceneResKey，提示用户
  if (uploadType.value === 'local' && !sceneForm.sceneResKey && !sceneForm.sceneImageUrl) {
    ElMessage.warning('图片上传未完成，请重新上传')
    return
  }
  
  saveLoading.value = true
  
  try {
    let sceneData = { ...sceneForm }
    
    // 添加上传类型标记
    sceneData.uploadType = uploadType.value
    
    // 添加ID
    if (!isEdit.value) {
      sceneData.id = ''
    } else {
      sceneData = { ...props.scenes[editIndex.value], ...sceneData }
    }
    
    // 添加剧本ID
    sceneData.dramaId = props.dramaId
    sceneData.id = sceneData.sceneId
    sceneData.name = sceneData.sceneName
    sceneData.desc = sceneData.sceneDesc
    sceneData.seriesNo = sceneData.seriesNo
    
    // 调试日志
    console.log('发送场景数据:', sceneData)
    
    // 调用API保存场景
    // 根据是否为编辑模式，调用不同的API
    if (isEdit.value) {
        // 编辑模式，调用更新API
      await updateScene(sceneData)
    } else {
      // 新增模式，调用创建API
      if (uploadType.value === 'local') {
        await createScene(sceneData)
      } else {
        await createSceneByAI(sceneData)
      }
    }
    
    // 刷新场景列表
    const { data } = await getDramaScene(props.dramaId)
    if (data && Array.isArray(data) && data.length > 0) {
      emit('update:scenes', data)
    }
    
    ElMessage.success(isEdit.value ? '场景更新成功' : '场景添加成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('保存场景失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saveLoading.value = false
  }
  } else {
    try {
      saveLoading.value = true
      await generateSceneBySeries(props.dramaId, seriesIdList.value)
      // 刷新场景列表
      const { data } = await getDramaScene(props.dramaId)
      if (data && Array.isArray(data) && data.length > 0) {
        emit('update:scenes', data)
      }
      
      ElMessage.success('场景添加成功')
      dialogVisible.value = false
    } catch (error) {
      console.error('保存场景失败:', error)
      ElMessage.error('保存失败，请重试')
    } finally {
      saveLoading.value = false
    }
  }
}

// 预生成弹窗相关
const preGenerateVisible = ref(false)
const currentScenePrompt = ref('')
const currentEditingScene = ref(null)
const confirmLoading = ref(false) // 添加确认场景图片的loading状态

// 场景图编辑弹窗相关
const sceneImageEditorVisible = ref(false)
const editingSceneImageUrl = ref('')
const editingSceneId = ref('')

// 打开预生成弹窗
const openPreGenerateDialog = (row) => {
  currentScenePrompt.value = row.sceneImagePrompt || ''
  currentEditingScene.value = row
  preGenerateVisible.value = true
}

// 处理预生成确认
const handlePreGenerateConfirm = async (imageUrl) => {
  if (!props.dramaId || !currentEditingScene.value?.sceneId || !imageUrl) {
    ElMessage.error('参数缺失，无法确认场景图片')
    return
  }
  
  confirmLoading.value = true // 开始加载
  
  // 创建全屏加载遮罩
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在绑定场景图片...',
  })
  
  try {
    // 调用确认接口
    await request.post('/evox-drama/scene/confirm', {
      dramaId: props.dramaId,
      sceneId: currentEditingScene.value.sceneId,
      name: currentEditingScene.value.sceneName,
      desc: currentEditingScene.value.sceneDesc,
      seriesNo: currentEditingScene.value.seriesNo,
      imagePrompt: currentScenePrompt.value.sceneImagePrompt,
      imageUrl
    })
    
    ElMessage.success('场景图片绑定成功')
    
    // 刷新场景列表
    try {
      const { data } = await getDramaScene(props.dramaId)
      if (data && Array.isArray(data)) {
        emit('update:scenes', data)
      }
    } catch (error) {
      console.error('获取场景列表失败:', error)
      ElMessage.error('获取场景列表失败，请手动刷新')
    }
  } catch (error) {
    console.error('场景图片确认失败:', error)
    ElMessage.error('场景图片绑定失败')
  } finally {
    // 关闭加载遮罩
    loadingInstance.close()
    confirmLoading.value = false // 结束加载
  // 重置当前编辑场景
  currentEditingScene.value = null
  }
}

// 处理PicUpload编辑事件
const handlePicUploadEdit = (editData) => {
  console.log('PicUpload编辑事件:', editData)
  
  // 等同于点击编辑场景图按钮
  if (!sceneForm.sceneImageUrl) {
    ElMessage.warning('场景图不存在，无法编辑')
    return
  }
  
  // 设置编辑参数
  editingSceneImageUrl.value = sceneForm.sceneImageUrl
  // 对于编辑场景，使用实际的sceneId；对于新建场景，传空字符串
  editingSceneId.value = isEdit.value ? 
    (sceneForm.sceneId || '') : 
    ''
  
  // 隐藏场景编辑弹窗
  dialogVisible.value = false
  
  // 打开图片编辑弹窗
  sceneImageEditorVisible.value = true
}

// 处理场景图编辑
const handleSceneImageEdit = () => {
  if (!sceneForm.sceneImageUrl) {
    ElMessage.warning('场景图不存在，无法编辑')
    return
  }
  
  // 设置编辑参数
  editingSceneImageUrl.value = sceneForm.sceneImageUrl
  // 对于编辑场景，使用实际的sceneId；对于新建场景，传空字符串
  editingSceneId.value = isEdit.value ? 
    (sceneForm.sceneId || '') : 
    ''
  
  // 隐藏场景编辑弹窗
  dialogVisible.value = false
  
  // 打开图片编辑弹窗
  sceneImageEditorVisible.value = true
}

// 处理场景图编辑弹窗关闭
const handleSceneImageEditorClose = () => {
  sceneImageEditorVisible.value = false
  editingSceneImageUrl.value = ''
  editingSceneId.value = ''
  
  // 重新打开场景编辑弹窗
  dialogVisible.value = true
}

// 处理场景图编辑保存
const handleSceneImageEditorSave = async (saveData) => {
  console.log('保存编辑后的场景图:', saveData)
  
  if (saveData && saveData.fileKey && saveData.originalUrl) {
    // 创建全局loading遮罩
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在保存场景...',
    })
    
    try {
      // 如果是编辑模式，使用当前场景参数创建新场景
      if (isEdit.value) {
        // 构建新场景数据
        const newSceneData = {
          sceneName: sceneForm.sceneName,
          sceneDesc: sceneForm.sceneDesc,
          seriesNo: sceneForm.seriesNo,
          sceneImageUrl: saveData.originalUrl,
          sceneResKey: saveData.fileKey,
          uploadType: 'local',
          dramaId: props.dramaId,
          id: '', // 新建场景，ID为空
          name: sceneForm.sceneName,
          desc: sceneForm.sceneDesc
        }
        
        console.log('使用编辑后的图片创建新场景:', newSceneData)
        
        // 调用创建场景API
        await createScene(newSceneData)
        
        // 刷新场景列表
        const { data } = await getDramaScene(props.dramaId)
        if (data && Array.isArray(data) && data.length > 0) {
          emit('update:scenes', data)
        }
        
        // 关闭所有弹窗
        sceneImageEditorVisible.value = false
        dialogVisible.value = false
        
        // 重置编辑状态
        isEdit.value = false
        editIndex.value = -1
        
      } else {
        // 新建场景模式，维持原有逻辑
        sceneForm.sceneImageUrl = saveData.originalUrl
        sceneForm.sceneResKey = saveData.fileKey
        
        ElMessage.success('场景图编辑完成')
        
        // 关闭图片编辑弹窗
        handleSceneImageEditorClose()
        
        // 重新打开场景编辑弹窗
        dialogVisible.value = true
      }
    } catch (error) {
      console.error('保存场景失败:', error)
      ElMessage.error('保存场景失败，请重试')
    } finally {
      // 关闭loading遮罩
      loadingInstance.close()
    }
  } else {
    ElMessage.warning('图片保存数据不完整')
  }
}
</script>

<style scoped>
.ai-tip {
  width: 100%;
  height: 110px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #64687A;
}
.scene-image {
  width: 45px;
  height: 45px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.scene-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 100%;
}

.uploaded-image {
  width: 100%;
  display: block;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 200px;
  color: #8c939d;
  background: #fff;
}

.upload-icon {
  font-size: 24px;
}

.upload-text {
  color: #525466;
  font-size: 14px;
  margin-top: 8px;
}

.scene-image-placeholder {
  cursor: pointer;
}
.disabled-color {
  color: #787C8F !important;
}

/* 单元格容器，用于定位 */
.scene-cell-container {
  position: relative;
  width: 100%;
  overflow: hidden;
  height: 100%;
  color: var(--theme-color, #1C1D29);
}

/* 单元格蒙层 */
.scene-cell-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.5);
  z-index: 1;
}

/* 第一列的蒙层，包含按钮 */
.scene-cell-overlay.first-column {
  display: flex;
  align-items: center;
  padding-left: 20px; /* 减小左侧距离，为按钮腾出空间 */
}

/* 按钮间距 */
.ml-2 {
  margin-left: 8px;
}

/* AI生成相关样式 */
.ai-placeholder {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 上传类型切换 */
.upload-type-switch {
  margin-bottom: 16px;
  padding: 4px;
  border-radius: 12px;
  background: #4764960F;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 186px;
}

/* 搜索结果为空的状态样式 */
.empty-search-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80px;
}

.empty-image {
  width: 240px;
  height: 240px;
}

.empty-text {
  font-size: 14px;
  color: #787C8F;
  margin: 20px 0;
}

/* 表单样式 */
.form-label {
  font-weight: normal;
  font-size: 14px;
  font-weight: 500;
  color: var(--theme-color, #1C1D29);
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.image-upload-container {
  width: 100%;
}

/* 场景图编辑按钮容器 */
.scene-edit-button-container {
  margin-top: 12px;
  display: flex;
  justify-content: center;
}

.scene-edit-btn {
  background-color: #3644E0;
  border-color: #3644E0;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
}

/* 对话框样式 */
.dialog-title {
  font-size: 16px;
  font-weight: 500;
  color: #1C1D29;
  line-height: 16px;
}

:deep(.scene-dialog .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

:deep(.el-upload-dragger) {
  width: 100%;
  background-color: transparent;
  border: none;
  padding: 0;
}

/* 图片预览样式 */
.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.image-preview-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.close-button {
  position: absolute;
  top: 32px;
  right: 32px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  font-size: 20px;
  transition: background-color 0.3s;
}
.error-message {
  width: 650px;
  margin: auto;
  padding-top: 186px;
}
.error-message-text {
  text-align: center;
  color:#787C8F;
  margin-top: 24px;
  font-size: 14px; 
}
.close-button:hover {
  background-color: rgba(255, 255, 255, 0.4);
}
:deep(.el-radio-button__inner) {
  background: transparent;
  border: 0 !important;
  border-radius: 12px !important;
}
:deep(.el-radio-button.is-active .el-radio-button__inner) {
  background: #fff !important;
}
.tab-wrapper {
  display: flex;
  gap: 32px;
  color: #1F2329;
  font-size: 14px;
}
.tab-item {
  position: relative;
  cursor: pointer;
}
.tab-item.active {
  color: #3644E0;
  font-weight: 500;
}
.tab-item.active:after {
  content: '';
  position: absolute;
  width: 24px;
  height: 3px;
  background: #3644E0;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
}
</style>